package dorm
import(
	"fmt"
	"os"
	"bufio"
	"strings"
	"io"
	"strconv"
)
type Config struct {
	filepath string
	conflist []map[string]map[string]string
}
func SetConfig(filepath string)(*Config,error) {
	c := new(Config)
	if _, err := os.Stat(filepath); err != nil {
		if os.IsNotExist(err) {
			panic("the file is not exist")
		}
       return c,err
	} else {
		c.filepath = filepath
		err:=c.readini()
		if err!=nil{
			fmt.Println(err.Error())
			return c,err
		}else{
			return c,nil
		}
	}
}

func (c * Config)Getvalue(section string, mykey string)string{
	conf :=c.conflist
	if section!="" {
		section=strings.TrimSpace(section)
		mykey=strings.TrimSpace(mykey)
		for _, v := range conf {
			if v!=nil{
				for key, value := range v {
					if key == section {
						if va,ok:=value[mykey]; ok{
							return va
						}
					}
				}
			}
		}
	}else{
		for _, v := range conf {
			for _, value := range v {
				myk,myva:=value[mykey]
				if myva{
					return myk
				}
			}
		}
	}
	return ""
}

func (c *Config)readini()error{
	f, err := os.Open(c.filepath)
	defer f.Close()
	if err != nil {
		return err
	}
	buf := bufio.NewReader(f)
	var data map[string]map[string]string
	var section,str string
	var j int=1
	for {
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		lenth:=len(line)
		if err == io.EOF||err != nil{
			break
		}
		if lenth==0{
           continue
		}

		if string(line[0])=="["  && string(line[lenth-1]) =="]"{
				section = strings.TrimSpace(line[1 : lenth-1])
				data = make(map[string]map[string]string)
				data[section] = make(map[string]string)
		}else{
				data = make(map[string]map[string]string)
				i := strings.IndexAny(line, "=")
				value := strings.TrimSpace(line[i+1 : lenth])
			    ke:=strings.TrimSpace(line[0:i])
			    if len(section)!=0{
					data[section] = make(map[string]string)
					data[section][ke] = value
					c.conflist = append(c.conflist, data)
				}else{
					str=strconv.Itoa(j)
					data[str]= make(map[string]string)
					data[str][ke] = value
					c.conflist = append(c.conflist, data)
					j++
				}
		}
	}

	return nil
}

func (c * Config)Output(){
	if len(c.conflist)==0{
		fmt.Println("error")
	}else{
		for  _,v:=range c.conflist{
			for key,value:=range v{
				fmt.Println(key,"::",value)
			}
		}
	}
}
/**
检测ini文件中是否已经存在此节点
 */
func (c *Config) uniquappend(conf string) bool {
	for _, v := range c.conflist {
		for k, _ := range v {
			if k == conf {
				return false
			}
		}
	}
	return true
}
